import 'dart:convert';

import 'package:decimal/decimal.dart';
import 'package:ecy_app_flutter/EcyRouter.dart';
import 'package:ecy_app_flutter/ecycommon/EcyAPI.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyAlipayUtil.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyLogger.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyWxUtil.dart';
import 'package:ecy_app_flutter/model/EcyLocationModel.dart';
import 'package:ecy_app_flutter/routes/consignment/model/ShopVo.dart';
import 'package:ecy_app_flutter/routes/goods/model/EcyGoodsSkuModel.dart';
import 'package:ecy_app_flutter/routes/pay/model/EcyOrderFinalPayModel.dart';
import 'package:ecy_app_flutter/routes/pay/model/EcyOrderPrePayModel.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../constant/EcyEventConsnt.dart';
import '../../constant/color_constant.dart';
import '../../ecycommon/EcyCommonWidgets.dart';
import '../../ecycommon/EcyEventBus.dart';
import '../../ecycommon/EcyRequestBaseManager.dart';
import '../../ecycommon/utils/EcyStorage.dart';
import '../../ecywidgtes/EcySwapBtn.dart';
import '../../model/EcyApiCommonPage.dart';
import '../../model/EcyApiCommonResponse.dart';
import '../goodscart/widgets/EcyGoodsCartItem2Widget.dart';
import '../my/model/order/CommoditySku.dart';

class EcyOrderConfirmPage extends EcyCommonBaseWidget {
  late final dynamic orderPrePayModel;
  late EcyOrderPrePayModel payModel;

  EcyOrderConfirmPage(this.orderPrePayModel)
      : payModel = EcyOrderPrePayModel.fromJson(jsonDecode(orderPrePayModel));

  @override
  _EcyOrderConfirmPageState createState() =>
      _EcyOrderConfirmPageState(payModel, this);
}

enum PayDeliveryType {
  quick, //快速配送
  byself, //门店自提
}

class _EcyOrderConfirmPageState extends EcyCommonBaseWidgetState {
  late EcyOrderPrePayModel payModel;
  late EcyOrderFinalPayModel? finalPayModel = null;
  final EcyCommonBaseWidget controller;
  late PayDeliveryType deliveryType = PayDeliveryType.quick; //配送方式
  ScrollController scrollController = ScrollController();
  bool leftSelected = true;
  // 实时运费 >= 150 = 0
  Decimal freight = Decimal.parse("0.00");
  // 运费
  Decimal _freight = Decimal.parse("0.00");
  // 商品总价
  Decimal _totalPrice = Decimal.parse("0.00");
  // 共多少件
  Decimal _totalNumber = Decimal.parse("0.00");
  ShopVo _shopVo = ShopVo();

  _EcyOrderConfirmPageState(this.payModel, this.controller);

  late List<EcyLocationModel> _ecyLocationModelList = [];

  late EcyLocationModel _locationModel = EcyLocationModel();

  @override
  void initState() {
    super.initState();
    refreshAddress();

    if(payModel.cartFlag ?? false) {
      refreshSkuStock(payModel);
    } else {
      refreshTotalData(payModel, []);
    }

    /// 获取运费
    getFreight();
    getShopInfo();
  }

  void refreshAddress() async {
    Map<String, dynamic> body = {
      "pageSize": 50,
      "pageIndex": 1,
    };
    var response = await EcyRequestbasemanager()
        .get("/app/api/app/user/address/list", body);
    if (response != null) {
      var _respModel =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (_respModel.code == 0 || _respModel.code == 200) {
        EcyApiCommonPage<EcyLocationModel> _modelPage =
            EcyApiCommonPage.fromJson(
                response["data"], (json) => EcyLocationModel.fromJson(json));
        setState(() {
          _ecyLocationModelList = _modelPage.records ?? [];
          _locationModel = _ecyLocationModelList.firstWhere(
              (e) => _locationModel.id != null
                  ? e.id == _locationModel.id
                  : e.addressDefault == 1,
              orElse: () => _ecyLocationModelList.isNotEmpty
                  ? _ecyLocationModelList[0]
                  : EcyLocationModel());
          setState(() {
            _locationModel = _locationModel;
          });
        });
      }
    }
  }

  void refreshSkuStock(EcyOrderPrePayModel order) async {
    var skuIds = order.skuList?.map((e) => e.skuId).toList();
    var response = await EcyRequestbasemanager()
        .get("/app/api/app/order/sku/stock", {}, skuIds);
    if (response != null) {
      var commonResponse =
        EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        List<CommoditySku> skuList = ((response["data"] ?? []) as List<dynamic>)
            .map((e) => CommoditySku.fromJson(e as Map<String, dynamic>))
            .toList();
        refreshTotalData(order, skuList);
      }
    }
  }

  EcyOrderPrePayModel refreshTotalData(EcyOrderPrePayModel order, List<CommoditySku> skuList) {
    Decimal totalPrice = Decimal.parse("0");
    Decimal totalNum = Decimal.parse("0");
    for (int i = 0; i < order.skuList!.length; i++) {
      EcyGoodsSkuModel item = order.skuList![i];
      var selectNum = Decimal.parse((item.selectNum ?? 0).toString());
      totalNum += selectNum;
      Decimal tempPrice = selectNum *
          Decimal.parse((item.salePrice ?? item.marketPrice ?? 0).toString());
      totalPrice += tempPrice;

      if(skuList.isNotEmpty) {
        var skuMap = { for (var item in skuList) item.id??"" : item };
        var sku = skuMap[item.skuId??""];
        if(sku != null) {
          item.stockQuantity = sku?.stockQuantity;
        }
      }
    }
    order.totalNum = totalNum.toString();
    order.totalPrice = totalPrice.toString();
    _totalPrice = Decimal.parse(order.totalPrice ?? "0.00");
    _totalNumber = Decimal.parse(order.totalNum ?? "0.00");
    if (_totalPrice >= Decimal.parse("150")) {
      freight = Decimal.parse("0");
    } else {
      freight = _freight;
    }
    return order;
  }

  /// 获取运费
  Future<void> getFreight() async {
    var response = await EcyRequestbasemanager().get(EcyAPI.freight.url, {});
    EcyLogger.tag(EcyAPI.freight.url, response);
    if (response['code'] == 0 || response['code'] == 200) {
      List<dynamic> data = response['data'];
      if (data.isNotEmpty) {
        String freight = data[0]['dictValue'];
        EcyLogger.tag("运费", freight);
        if (freight.isNotEmpty) {
          setState(() {
            if (_totalPrice < Decimal.parse("150")) {
              this.freight = Decimal.parse(freight);
            }
            _freight = Decimal.parse(freight);
          });
        }
      }
    }
  }

  /// 获取门店信息
  Future<void> getShopInfo() async {
    var response = await EcyRequestbasemanager()
        .get("${EcyAPI.shop.url}${payModel.shopId}", {});
    if (response['code'] == 0 || response['code'] == 200) {
      if (response['data'] != null) {
        // setState(() {
        _shopVo = ShopVo.fromJson(response['data']);
        // });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: true,
        backgroundColor: const Color(0xFFF5F5F5),
        appBar: AppBar(
          leading: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              EcyRouter.pop(context, "");
            },
            child: Align(
              alignment: Alignment.centerRight,
              child: Image.asset(
                "assets/images/ic_back.png",
                width: 30.w,
              ),
            ),
          ),
          scrolledUnderElevation: 0,
          backgroundColor: ColorConstant.White,
          title: const Text(
            '确认订单',
            style: TextStyle(fontSize: 18),
          ),
          centerTitle: true,
        ),
        bottomNavigationBar: BottomAppBar(
          color: Colors.white,
          // shape: CircularNotchedRectangle(), // 底部导航栏打一个圆形的洞
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Expanded(
                flex: 1,
                child: Container(
                  height: 40.0,
                  padding: const EdgeInsets.only(left: 0),
                  child: Container(
                      color: ColorConstant.CommonColorWhite,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          Expanded(
                              child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              SizedBox(width: 4.w),
                              Text('共$_totalNumber件,',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontWeight: FontWeight.w500,
                                      fontSize: 14.sp,
                                      color: const Color(0xFF8C8C8C))),
                              SizedBox(width: 14.w),
                              Text("合计: ",
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontWeight: FontWeight.w500,
                                      fontSize: 14.sp,
                                      color: const Color(0xFF262626))),
                              Text("¥ ${_totalPrice + freight}",
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontWeight: FontWeight.w700,
                                      fontSize: 16.sp,
                                      color: const Color(0xFFF55F4E))),
                            ],
                          )),
                          GestureDetector(
                            child: Container(
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(26.r),
                                color: ColorConstant.CommonColor,
                              ),
                              width: 110.w,
                              height: 40.h,
                              alignment: Alignment.center,
                              child: Text('立即支付',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontWeight: FontWeight.w700,
                                      fontSize: 16.sp,
                                      color: ColorConstant.White)),
                            ),
                            onTap: () {
                              pay();
                            },
                          )
                        ],
                      )),
                ),
              )
            ],
          ),
        ),
        body: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: EdgeInsets.only(bottom: 44.h),
          controller: scrollController,
          child: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                //触摸收起键盘
                FocusScope.of(context).requestFocus(FocusNode());
              },
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          width: EcyPageUtil.screenWidth(context),
                          color: const Color(0xffffffff),
                          height: 44.h,
                          child: Center(
                              child: EcySwapBtn(
                                  "快递配送",
                                  const Color(0xFFEA4B9B),
                                  const Color(0xFFF5F5F5),
                                  const Color(0xFFFFFFFF),
                                  const Color(0xFF262626),
                                  "门店自提",
                                  const Color(0xFFEA4B9B),
                                  const Color(0xFFF5F5F5),
                                  const Color(0xFFFFFFFF),
                                  const Color(0xFF262626), () {
                            setState(() {
                              leftSelected = true;
                              freight = _totalPrice >= Decimal.parse("150")
                                  ? Decimal.zero
                                  : _freight;
                            });
                          }, () {
                            setState(() {
                              leftSelected = false;
                              freight = Decimal.zero;
                            });
                          })),
                        ),
                        leftSelected
                            ? GestureDetector(
                                onTap: () {
                                  EcyRouter().push(
                                      context, EcyRouter.addressPage, {
                                    "checkFlag": true,
                                    "locationId": _locationModel.id
                                  }).then((val) {
                                    refreshAddress();
                                    if (val != null) {
                                      refreshAddress();
                                      setState(() {
                                        _locationModel = val;
                                      });
                                    }
                                  });
                                },
                                child: Card(
                                    margin: EdgeInsets.only(
                                        left: 16.w,
                                        right: 16.w,
                                        top: 16.w,
                                        bottom: 0.w),
                                    color: Colors.white,
                                    child: ListTile(
                                      title: Padding(
                                          padding: const EdgeInsets.all(0),
                                          child: _ecyLocationModelList.isEmpty
                                              ? SizedBox(
                                                  width: MediaQuery.of(context)
                                                      .size
                                                      .width,
                                                  child: TextButton(
                                                      onPressed: () {
                                                        EcyRouter()
                                                            .push(
                                                                context,
                                                                EcyRouter
                                                                    .addressEditPage,
                                                                EcyLocationModel
                                                                    .fromJson(
                                                                        {}))
                                                            .then((val) {
                                                          refreshAddress();
                                                        });
                                                      },
                                                      style: const ButtonStyle(
                                                        alignment:
                                                            Alignment.center,
                                                        foregroundColor:
                                                            WidgetStatePropertyAll(
                                                                Color(
                                                                    0xFFEA4B9B)),
                                                        overlayColor:
                                                            WidgetStatePropertyAll(
                                                                Colors
                                                                    .transparent),
                                                      ),
                                                      child: Text(
                                                        '添加收货地址',
                                                        style: TextStyle(
                                                          fontFamily:
                                                              "PingFang SC",
                                                          fontWeight:
                                                              FontWeight.w400,
                                                          fontSize: 14.sp,
                                                          leadingDistribution:
                                                              TextLeadingDistribution
                                                                  .even, // 设置leading策略
                                                        ),
                                                      )),
                                                )
                                              : Row(
                                                  children: [
                                                    Expanded(
                                                        flex: 1,
                                                        child: SizedBox(
                                                          height: 16,
                                                          child: Image.asset(
                                                              'assets/images/ic_order_location.png',
                                                              width: 16),
                                                        )),
                                                    Expanded(
                                                        flex: 7,
                                                        child: Container(
                                                          padding:
                                                              const EdgeInsets
                                                                  .all(6),
                                                          child: Column(
                                                            crossAxisAlignment:
                                                                CrossAxisAlignment
                                                                    .start,
                                                            children: [
                                                              Row(
                                                                mainAxisAlignment:
                                                                    MainAxisAlignment
                                                                        .start,
                                                                children: [
                                                                  Text(
                                                                      (_locationModel?.contact ??
                                                                          " ${_locationModel?.phone ?? ""}"),
                                                                      style: TextStyle(
                                                                          fontFamily:
                                                                              "PingFang SC",
                                                                          fontWeight: FontWeight
                                                                              .w700,
                                                                          fontSize: 16
                                                                              .sp,
                                                                          color: const Color(
                                                                              0xFF262626)),
                                                                      maxLines:
                                                                          1,
                                                                      overflow:
                                                                          TextOverflow
                                                                              .ellipsis),
                                                                  const Padding(
                                                                      padding: EdgeInsets.only(
                                                                          right:
                                                                              10)),
                                                                  if (_locationModel
                                                                          .addressDefault ==
                                                                      1)
                                                                    DecoratedBox(
                                                                        decoration:
                                                                            BoxDecoration(
                                                                          borderRadius:
                                                                              BorderRadius.circular(50.0), //3像素圆角
                                                                          border:
                                                                              Border.all(
                                                                            color:
                                                                                const Color(0xFFEA4B9B),
                                                                            width:
                                                                                1.0,
                                                                          ),
                                                                        ),
                                                                        child:
                                                                            const Padding(
                                                                          padding: EdgeInsets.symmetric(
                                                                              horizontal: 7,
                                                                              vertical: 1),
                                                                          child:
                                                                              Text(
                                                                            "默认",
                                                                            style:
                                                                                TextStyle(fontSize: 10, color: Color(0xFFEA4B9B)),
                                                                          ),
                                                                        ))
                                                                ],
                                                              ),
                                                              const Padding(
                                                                  padding: EdgeInsets
                                                                      .only(
                                                                          bottom:
                                                                              3)),
                                                              Text(
                                                                  (_locationModel?.provinceName ?? "") +
                                                                      (_locationModel
                                                                              ?.cityName ??
                                                                          "") +
                                                                      (_locationModel
                                                                              ?.areaName ??
                                                                          "") +
                                                                      (_locationModel
                                                                              ?.streetName ??
                                                                          "") +
                                                                      (_locationModel
                                                                              ?.detail ??
                                                                          ""),
                                                                  style: TextStyle(
                                                                      fontFamily:
                                                                          "PingFang SC",
                                                                      fontWeight:
                                                                          FontWeight
                                                                              .w400,
                                                                      fontSize:
                                                                          14.sp,
                                                                      color: const Color(
                                                                          0xFF8C8C8C)),
                                                                  maxLines: 2,
                                                                  overflow:
                                                                      TextOverflow
                                                                          .ellipsis),
                                                            ],
                                                          ),
                                                        )),
                                                  ],
                                                )),
                                      trailing: const Icon(
                                        Icons.arrow_forward_ios,
                                        size: 14,
                                      ),
                                      splashColor: Colors.transparent,
                                      onTap: () {
                                        EcyRouter().push(
                                            context, EcyRouter.addressPage, {
                                          "checkFlag": true,
                                          "locationId": _locationModel.id
                                        }).then((val) {
                                          refreshAddress();
                                          if (val != null) {
                                            refreshAddress();
                                            setState(() {
                                              _locationModel = val;
                                            });
                                          }
                                        });
                                      },
                                    )),
                              )
                            : _shopVo.id != null
                                ? Card(
                                    margin: EdgeInsets.only(
                                        left: 16.w,
                                        right: 16.w,
                                        top: 16.w,
                                        bottom: 0.w),
                                    color: Colors.white,
                                    child: Padding(
                                        padding: const EdgeInsets.only(
                                            top: 10,
                                            bottom: 10,
                                            left: 10,
                                            right: 10),
                                        child: Column(
                                          children: [
                                            Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.start,
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                Padding(
                                                    padding:
                                                        const EdgeInsets.only(
                                                            top: 8,
                                                            bottom: 10,
                                                            left: 10,
                                                            right: 0),
                                                    child: SizedBox(
                                                      height: 14,
                                                      child: Image.asset(
                                                          'assets/images/pay/icon_confirm_shop.png',
                                                          width: 14),
                                                    )),
                                                Expanded(
                                                    flex: 7,
                                                    child: Container(
                                                      padding:
                                                          const EdgeInsets.all(
                                                              6),
                                                      child: Column(
                                                        crossAxisAlignment:
                                                            CrossAxisAlignment
                                                                .start,
                                                        children: [
                                                          Row(
                                                            mainAxisAlignment:
                                                                MainAxisAlignment
                                                                    .start,
                                                            children: [
                                                              Text(
                                                                "${_shopVo.name}",
                                                                style: TextStyle(
                                                                    fontFamily:
                                                                        "PingFang SC",
                                                                    fontWeight:
                                                                        FontWeight
                                                                            .w500,
                                                                    fontSize:
                                                                        14.sp,
                                                                    color: const Color(
                                                                        0xFF262626)),
                                                              )
                                                            ],
                                                          ),
                                                          const Padding(
                                                              padding: EdgeInsets
                                                                  .only(
                                                                      bottom:
                                                                          3)),
                                                          Text(
                                                            '${_shopVo.provinceName ?? ""}'
                                                            '${_shopVo.cityName ?? ""}'
                                                            '${_shopVo.areaName ?? ""}'
                                                            '${_shopVo.address ?? ""}',
                                                            style: TextStyle(
                                                                fontFamily:
                                                                    "PingFang SC",
                                                                fontWeight:
                                                                    FontWeight
                                                                        .w400,
                                                                fontSize: 14.sp,
                                                                color: const Color(
                                                                    0xFF8C8C8C)),
                                                          ),
                                                        ],
                                                      ),
                                                    )),
                                              ],
                                            ),
                                            Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.start,
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                Padding(
                                                    padding:
                                                        const EdgeInsets.only(
                                                            top: 8,
                                                            bottom: 10,
                                                            left: 10,
                                                            right: 0),
                                                    child: SizedBox(
                                                      height: 14,
                                                      child: Image.asset(
                                                          'assets/images/pay/icon_confirm_contact.png',
                                                          width: 14),
                                                    )),
                                                Expanded(
                                                    flex: 7,
                                                    child: Container(
                                                      padding:
                                                          const EdgeInsets.all(
                                                              6),
                                                      child: Column(
                                                        crossAxisAlignment:
                                                            CrossAxisAlignment
                                                                .start,
                                                        children: [
                                                          Row(
                                                            mainAxisAlignment:
                                                                MainAxisAlignment
                                                                    .start,
                                                            children: [
                                                              Text(
                                                                  "${_shopVo.liaison ?? ""}  ${_shopVo.contact ?? ""}",
                                                                  style: TextStyle(
                                                                      fontFamily:
                                                                          "PingFang SC",
                                                                      fontWeight:
                                                                          FontWeight
                                                                              .w500,
                                                                      fontSize:
                                                                          14.sp,
                                                                      color: const Color(
                                                                          0xFF262626)),
                                                                  maxLines: 1,
                                                                  overflow:
                                                                      TextOverflow
                                                                          .ellipsis)
                                                            ],
                                                          )
                                                        ],
                                                      ),
                                                    )),
                                              ],
                                            )
                                          ],
                                        )))
                                : Container(),
                        Card(
                            color: Colors.white,
                            margin: EdgeInsets.only(
                                left: 16.w,
                                right: 16.w,
                                top: 10.w,
                                bottom: 0.w),
                            child: Padding(
                              padding: const EdgeInsets.only(
                                  top: 10, bottom: 10, left: 10, right: 10),
                              child: Column(
                                children: [
                                  ListView.builder(
                                      shrinkWrap: true,
                                      physics:
                                          const NeverScrollableScrollPhysics(),
                                      scrollDirection:
                                          Axis.vertical, // 设置滚动方向为s水平
                                      itemCount: payModel.skuList?.length,
                                      itemBuilder: (context, index) {
                                        var item = payModel.skuList?[index];
                                        EcyGoodsCartItem2Widget itemWidget =
                                            EcyGoodsCartItem2Widget(
                                          item!,
                                          (onOpeNumlValue) {
                                            payModel.skuList?[index] =
                                                onOpeNumlValue;
                                            refreshTotalData(payModel, []);
                                            setState(() {
                                              payModel = payModel;
                                            });
                                          },
                                        );
                                        return itemWidget;
                                      }),
                                  Container(
                                      margin: EdgeInsets.only(
                                          left: 0.w,
                                          right: 0.w,
                                          top: 10.w,
                                          bottom: 0.w),
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                            "商品总价",
                                            style: TextStyle(
                                                fontSize: 14.sp,
                                                fontWeight: FontWeight.w500,
                                                color: Colors.black),
                                          ),
                                          Text(
                                            "¥$_totalPrice",
                                            style: TextStyle(
                                                fontSize: 14.sp,
                                                fontWeight: FontWeight.w500,
                                                color: Colors.black),
                                          )
                                        ],
                                      )),
                                  Container(
                                      margin: EdgeInsets.only(
                                          left: 0.w,
                                          right: 0.w,
                                          top: 10.w,
                                          bottom: 0.w),
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                            "运费",
                                            style: TextStyle(
                                                fontSize: 14.sp,
                                                fontWeight: FontWeight.w500,
                                                color: Colors.black),
                                          ),
                                          Text(
                                            "¥$freight",
                                            style: TextStyle(
                                                fontSize: 14.sp,
                                                fontWeight: FontWeight.w500,
                                                color: Colors.black),
                                          )
                                        ],
                                      )),
                                  Container(
                                      margin: EdgeInsets.only(
                                          left: 0.w,
                                          right: 0.w,
                                          top: 10.w,
                                          bottom: 0.w),
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                            "合计",
                                            style: TextStyle(
                                                fontSize: 14.sp,
                                                fontWeight: FontWeight.w500,
                                                color: Colors.black),
                                          ),
                                          Text(
                                            "¥${_totalPrice + freight}",
                                            style: TextStyle(
                                                fontSize: 14.sp,
                                                fontWeight: FontWeight.w500,
                                                color: Colors.black),
                                          )
                                        ],
                                      )),
                                ],
                              ),
                            )),
                        Card(
                            margin: EdgeInsets.only(
                                left: 16.w,
                                right: 16.w,
                                top: 10.w,
                                bottom: 0.w),
                            color: Colors.white,
                            child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 10, bottom: 10, left: 10, right: 10),
                                child: Column(children: [
                                  GestureDetector(
                                    child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Row(
                                            children: [
                                              SizedBox(
                                                height: 16,
                                                child: Image.asset(
                                                    'assets/images/pay/icon_confirm_wx.png',
                                                    width: 16),
                                              ),
                                              SizedBox(width: 8.w),
                                              Text(
                                                "微信",
                                                style: TextStyle(
                                                    fontSize: 14.sp,
                                                    fontWeight: FontWeight.w500,
                                                    color: Color(0xFF262626)),
                                              ),
                                            ],
                                          ),
                                          SizedBox(
                                            height: 18,
                                            child: Image.asset(
                                                (payModel.payWay ?? "0") == "0"
                                                    ? 'assets/images/pay/icon_confirm_checked.png'
                                                    : 'assets/images/pay/icon_confirm_unchecked.png',
                                                width: 18),
                                          ),
                                        ]),
                                    onTap: () {
                                      selectPayWay("0");
                                    },
                                  ),
                                  SizedBox(height: 10.h),
                                  GestureDetector(
                                    child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Row(
                                            children: [
                                              SizedBox(
                                                height: 16,
                                                child: Image.asset(
                                                    'assets/images/pay/icon_confirm_zfb.png',
                                                    width: 16),
                                              ),
                                              SizedBox(width: 8.w),
                                              Text(
                                                "支付宝",
                                                style: TextStyle(
                                                    fontSize: 14.sp,
                                                    fontWeight: FontWeight.w500,
                                                    color: const Color(
                                                        0xFF262626)),
                                              ),
                                            ],
                                          ),
                                          SizedBox(
                                            height: 18,
                                            child: Image.asset(
                                                (payModel.payWay ?? "0") == "1"
                                                    ? 'assets/images/pay/icon_confirm_checked.png'
                                                    : 'assets/images/pay/icon_confirm_unchecked.png',
                                                width: 18),
                                          ),
                                        ]),
                                    onTap: () {
                                      selectPayWay("1");
                                    },
                                  ),
                                ]))),
                        Card(
                            margin: EdgeInsets.only(
                                left: 16.w,
                                right: 16.w,
                                top: 10.w,
                                bottom: 0.w),
                            color: Colors.white,
                            child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 10, bottom: 10, left: 10, right: 10),
                                child: Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        "订单备注",
                                        style: TextStyle(
                                            fontSize: 14.sp,
                                            fontWeight: FontWeight.w500,
                                            color: Colors.black),
                                      ),
                                      Container(
                                        width: 250.w,
                                        child: TextField(
                                            onChanged: (value) {
                                              payModel.notes = value;
                                            },
                                            textAlign: TextAlign.end,
                                            style: TextStyle(
                                                fontFamily: "PingFag SC",
                                                fontWeight: FontWeight.w500,
                                                fontSize: 14.sp,
                                                color: ColorConstant
                                                    .CommonColorBlack),
                                            maxLines: 1,
                                            maxLength: 100,
                                            maxLengthEnforcement:
                                                MaxLengthEnforcement
                                                    .truncateAfterCompositionEnds,
                                            keyboardType:
                                                TextInputType.multiline,
                                            decoration: InputDecoration(
                                              isDense: true,
                                              counterText: '',
                                              hintText: "输入订单备注内容",
                                              hintStyle: const TextStyle(
                                                color: Colors.grey,
                                              ),
                                              border: OutlineInputBorder(
                                                borderRadius:
                                                    BorderRadius.circular(5),
                                                borderSide: BorderSide.none,
                                              ),
                                              //是否填充背景色
                                              filled: true,
                                              //设置背景色，filled 为 true 时生效
                                              fillColor: Color(0xffffff),
                                              contentPadding:
                                                  const EdgeInsets.all(5.0),
                                            ),
                                            onSubmitted: (event) {
                                              FocusScope.of(context)
                                                  .focusedChild
                                                  ?.unfocus();
                                            }),
                                      )
                                    ]))),
                      ],
                    )
                  ])),
        ));
  }

  // 提交订单
  Future<bool> commitOrder() async {
    var orderItems = [];
    for (int i = 0; i < payModel.skuList!.length; i++) {
      EcyGoodsSkuModel item = payModel.skuList![i];
      var currNum = Decimal.parse((item.selectNum ?? 0).toString());
      var salePrice =
          Decimal.parse((item.salePrice ?? item.marketPrice ?? 0).toString());
      Decimal tempPrice = currNum * salePrice;
      orderItems.add({
        "commoditySkuId": item.skuId,
        "price": salePrice,
        "num": currNum,
        "totalPrice": tempPrice
      });
    }
    var response = await EcyRequestbasemanager().postWithHeader(
        {"X-Api-Version": "1.1"},
        "app/api/app/order/create",
        {
          "orderType": payModel?.orderType ?? 0,
          "shippingId": _locationModel?.id,
          "shippingMethod": leftSelected ? 0 : 1, // 0普通快递 1|自提
          "shopId": payModel.shopId,
          "note": payModel.notes ?? "",
          "postage": freight,
          "lat": _locationModel?.lat ?? 0,
          "lng": _locationModel?.lng ?? 0,
          "orderItems": orderItems,
          "pay": {
            "channel": payModel.payWay ?? "0",
            "amount": 0,
            "lat": _locationModel?.lat ?? 0,
            "lng": _locationModel?.lng ?? 0,
          }
        });
    controller.dismissLoading();
    EasyLoading.dismiss();
    if (response != null &&
        (response["code"] == 0 || response["code"] == 200)) {
      EcyOrderFinalPayModel resp =
          EcyOrderFinalPayModel.fromJson(response["data"]);
      finalPayModel = resp;
      EcyStorage.setString(EcyEventConst.kPayedOrderId, resp.orderId);
      return true;
    } else {
      EasyLoading.showToast(response["msg"] ?? "支付失败",
          duration: const Duration(seconds: 2));
      return false;
    }
  }

  pay() async {
    if (leftSelected && (_locationModel.id == null || _locationModel.id!.isEmpty)) {
      EasyLoading.showToast("请添加收货地址", duration: const Duration(seconds: 2));
      return;
    }
    EasyLoading.show(status: '支付中...', dismissOnTap: false);
    try {
      bool prePay = await commitOrder();
      if (prePay) {
        if (finalPayModel?.channel == 1) {
          dynamic payInfo = await getPayInfo();
          EcyAlipayUtil().startPay(payInfo, context);
        } else {
          String payInfo = await getPayInfo();
          bool wechatFlag =
              await EcyWxUtil().pay(json.decode(payInfo), context);
          if (!wechatFlag) {
            EasyLoading.showToast("微信支付失败，请稍后再试",
                duration: const Duration(seconds: 2));
          }
        }
      }
      // else {
      //   EasyLoading.showToast("请稍后再试...", duration: const Duration(seconds: 2));
      // }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    } finally {
      EcyEventBus().emit(EcyEventConst.kCartChanged);
      EasyLoading.dismiss();
    }
  }

  Future<String> getPayInfo() async {
    var response = await EcyRequestbasemanager().post(EcyAPI.pay.url,
        {"channel": finalPayModel?.channel, "orderId": finalPayModel?.orderId});
    return response["data"];
  }

  selectPayWay(String payWay) {
    if (payModel != null) {
      payModel.payWay = payWay;
    }
    if (finalPayModel != null) {
      finalPayModel?.channel = int.parse(payWay);
    }

    setState(() {
      payModel = payModel;
    });
  }
}
